package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.rmi.registry.Registry;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;
    /*
    * 微信登录
    * */
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {

        /*
        * 调用微信接口服务，获取当前微信用户的openid
        * */
        String openid = getOpenid(userLoginDTO);

        /*
        * 判断openid是否为空，为空则失败，抛出异常
        * */
        if(openid==null){
            throw new LoginFailedException("用户登录异常");
        }

        /*
        * 判断当前用户是否为新用户,如果是老用户,则返回User对象
        * */
        User userByOpenid = userMapper.getByOpenid(openid);
        if(userByOpenid!=null){
            return userByOpenid;
        }

        /*
        * 如果是新用户，自动完成注册功能
        * */
        else {
            return UserRegistryByOpenid(openid);
        }

    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        //微信请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",  weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        //返回json字符串
        String resultJson = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);

        JSONObject jsonObject = JSON.parseObject(resultJson);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    private User UserRegistryByOpenid(String openid) {

        User user = new User();
        user.setOpenid(openid);
        user.setCreateTime(LocalDateTime.now());

        return userMapper.saveUserForRegistry(user);
    }
}
